import {createApp} from 'vue'
import App from './App.vue'

import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import "@/assets/style/index.scss"
import "@/assets/style/theme.scss"
import router from './router'
import store from './store'
import other from "./utils/other"
import getDirective from "./directive/index"
import {setToken, getToken} from "./utils/auth";
import Modal from "@/components/modal/index"
import layout from "@/views/layout/layout";

const app = createApp(App)
other.component(app);
getDirective.component(app);
other.elSvg(app);

const whiteList = ['/login']

router.beforeEach((to, from, next) => {
  if (getToken()) {
    if (to.path === '/login') {
      next({path: '/'})
    } else {
      if (store.state.user.roles.length == 0) {
        store.dispatch("user/GetInfo").then(() => {
          store.dispatch("user/GenerateRoutes").then(accessRoutes => {
            filterAsyncRouter(accessRoutes)
            next({...to, replace: true}) // hack方法 确保addRoutes已完成
          })
        })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next({path: "/login"}); // 否则全部重定向到登录页
    }
  }
})
const loadView = (view) => { // 路由懒加载
  return () => require.ensure([],(require)=>require(`@/views/${view}.vue`))
}

function filterAsyncRouter(asyncRouterMap, routers) {
   asyncRouterMap.forEach((route,index) => {
    if (route.component && route.children == null) {
      router.addRoute("layout", {
        path: `/${route.path}`,
        name: route.name,
        math:route.math,
        // component: () => import(`@/views/brand/brand`)
        component: loadView(route.component)
      });
    }
    if (route.children != null && route.children && route.children.length) {
     filterAsyncRouter(route.children, routers)
    }
  })
}
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

// app.config.globalProperties.$VERSION = VERSION


app.use(store).use(ElementPlus, {
  locale: zhCn,
}).use(router).use(Modal).mount('#app')
